import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/module/match/list/lq_end_logic.dart';
import 'package:ball_lion/module/match/list/lq_match_filter_logic.dart';
import 'package:ball_lion/module/match/list/lq_notbegin_logic.dart';
import 'package:ball_lion/module/match/list/match_page_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/entity/match/lq_list_entity.dart';
import 'package:ball_lion/entity/match/zq_list_entity.dart';
import 'package:ball_lion/server/api/basketball_api.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/user.dart';

class LqViewLogic extends GetxController implements MatchListProvider {
  LqViewLogic(this.type, this.tag, {this.date, this.hotId, this.hotLabel});

  LqMatchType type;
  String tag;
  DateTime? date;
  String? hotId;
  String? hotLabel;
  final refreshC = EasyRefreshController();

  late LqMatchFilterLogic filter;
  final scrollC = ApmScrollController();
  //所有比赛
  List<LqListEntity> originalData = [];
  //筛选比赛
  // List<LqListEntity> filterData = [];
  List<DateTime>? dayList;
  List<List<LqListEntity>>? groupMatchList;
  List<LqListEntity> matchList = [];
  bool firstLoad = true;
  //01234 全部 一级 竞足 方案 情报
  QuickFilter quickFilter = QuickFilter.all;
  bool isBottomHide = false;
  // var showTop = false.obs;
  int hideMatchNum = 0;
  bool isScrollDown = false;

  @override
  void onInit() {
    super.onInit();
    if (tag == Constant.matchFilterTagHot) {
      filter = Get.find<LqMatchFilterLogic>(tag: "$tag$hotLabel");
    } else {
      filter = Get.find<LqMatchFilterLogic>(tag: tag);
    }
    scrollC.addListener(() {
      if (scrollC.offset < 0 && !isScrollDown) {
        isScrollDown = true;
        update();
      } else if (scrollC.offset > 9 && isScrollDown) {
        isScrollDown = false;
        update();
      }
      Get.find<NavigationLogic>().onMatchPageScroll();
    });
  }

  updateView() {
    update();
  }

  @override
  void onReady() {
    super.onReady();
    getMatch();
  }

  @override
  Future getMatch() async {
    List<LqListEntity>? matchList;
    var hotMatchId = hotId ?? '';
    var hotTeamId = "";
    if (hotId?.contains("-") ?? false) {
      hotMatchId = hotId?.split('-')[0] ?? '';
      hotTeamId = hotId?.split('-')[1] ?? '';
    }
    if (type == LqMatchType.hot) {
      matchList =
          await BasketballApi.getLqHotList(hotMatchId, teamId: hotTeamId);
    } else if (type == LqMatchType.all) {
      matchList = await BasketballApi.getLqAllList();
    } else if (type == LqMatchType.begin) {
      matchList = await BasketballApi.getLqBeginList();
    } else if (type == LqMatchType.schedule) {
      matchList = await BasketballApi.getLqNotBeginList(
          DateTimeUtils.formatDateTime(date!, 'yyyy-MM-dd'));
    } else if (type == LqMatchType.end) {
      matchList = await BasketballApi.getLqResultList(
          DateTimeUtils.formatDateTime(date!, 'yyyy-MM-dd'));
    } else if (type == LqMatchType.focus) {
      if (!User.isLogin) {
        return;
      }
      matchList = await BasketballApi.getLqFocusList();
    }

    if (matchList != null) {
      originalData = matchList;
      if (firstLoad) {
        filter.initLeague(type);
        quickFilter = filter.quickFilter;
      }
      filterMatch(filter.getHideLeagueIdList());
      firstLoad = false;
      update();
    }
  }

  void filterMatch(List<int> hideLeagueId) {
    isBottomHide = false;
    List<LqListEntity> matchListTemp = [];
    hideMatchNum = 0;
    for (var match in originalData) {
      if (quickFilter == QuickFilter.qingbao && match.intelligence == 0) {
        hideMatchNum++;
        continue;
      }
      if (quickFilter == QuickFilter.guandian && match.planCnt == 0) {
        hideMatchNum++;
        continue;
      }
      if (!hideLeagueId.contains(match.leagueId)) {
        if (filter.leagueType == LqFilterType.jc && match.jcNo != null) {
          matchListTemp.add(match);
        } else {
          matchListTemp.add(match);
        }
      }
    }
    if (quickFilter == QuickFilter.yiji ||
        quickFilter == QuickFilter.jingcai ||
        quickFilter == QuickFilter.all) {
      hideMatchNum = filter.hideMatchNum;
    }
    if (type == LqMatchType.schedule || type == LqMatchType.end) {
      if (matchListTemp.isNotEmpty) {
        matchListTemp.first.showTopSpace = true;
      }
      matchList = matchListTemp;
      if (type == LqMatchType.schedule) {
        Get.find<LqNotBeginLogic>().hideMatchNum = hideMatchNum;
        Get.find<LqNotBeginLogic>().onShowBottom();
      } else {
        Get.find<LqEndLogic>().hideMatchNum = hideMatchNum;
        Get.find<LqEndLogic>().onShowBottom();
      }
      update();
    } else {
      groupData(matchListTemp);
    }
  }

  void groupData(List<LqListEntity> matchList) {
    List<DateTime> dateListTemp = [];
    List<List<LqListEntity>> groupMatchListTemp = [];
    //同一天比赛
    List<LqListEntity> sameDayMatchList = [];
    List<LqListEntity> endMatchList = [];
    bool hasEnd = false;
    for (int i = 0; i < matchList.length; i++) {
      LqListEntity match = matchList[i];
      final dateTime = DateTime.parse(match.matchTime!);
      if (dateListTemp.isEmpty) {
        if ((type == LqMatchType.hot || type == LqMatchType.focus) &&
            match.hasEnd()) {
          endMatchList.add(match);
          hasEnd = true;
        } else {
          dateListTemp.add(dateTime);
          sameDayMatchList.add(match);
        }
      } else if (DateUtils.isSameDay(dateListTemp.last, dateTime)) {
        sameDayMatchList.add(match);
      } else {
        groupMatchListTemp.add(sameDayMatchList);
        matchList[i - 1].lastMatchInDay = true;
        dateListTemp.add(dateTime);
        sameDayMatchList = [match];
      }
    }
    //加上最后一天比赛
    if (sameDayMatchList.length > 0) {
      groupMatchListTemp.add(sameDayMatchList);
    }
    if (hasEnd) {
      dateListTemp.add(DateTime(1999));
      groupMatchListTemp.add(endMatchList.reversed.toList());
    }
    dayList = dateListTemp;
    groupMatchList = groupMatchListTemp;
    update();
  }

  onSelectMatchType(QuickFilter filterType, {bool fromFilterPage = false}) {
    quickFilter = filterType;
    if (Get.find<ConfigService>().zqConfig.zqAlert7 == 1) {
      try {
        Get.find<LqViewLogic>(tag: Constant.matchFilterTagAll)
            .filterMatchByType(filterType);
      } catch (e) {}
      if (type != LqMatchType.hot) {
        try {
          Get.find<LqViewLogic>(tag: "${Constant.matchFilterTagHot}$hotLabel")
              .filterMatchByType(filterType);
        } catch (e) {}
      }
      if (type != LqMatchType.begin) {
        try {
          Get.find<LqViewLogic>(tag: Constant.matchFilterTagBegin)
              .filterMatchByType(filterType);
        } catch (e) {}
      }
      if (type != LqMatchType.schedule) {
        try {
          final logic = Get.find<LqNotBeginLogic>();
          logic.quickFilter = filterType;
          Get.find<LqViewLogic>(
                  tag: '${Constant.matchFilterTagSchedule}${logic.index}')
              .filterMatchByType(filterType);
        } catch (e) {}
      }
      if (type != LqMatchType.end) {
        try {
          final logic = Get.find<LqEndLogic>();
          logic.quickFilter = filterType;
          Get.find<LqViewLogic>(
                  tag: '${Constant.matchFilterTagResult}${logic.index}')
              .filterMatchByType(filterType);
        } catch (e) {}
      }
    }
    if (!fromFilterPage) {
      filterMatchByType(filterType);
    }
  }

  filterMatchByType(QuickFilter index) {
    quickFilter = index;
    if (quickFilter == QuickFilter.all) {
      onSelectDefaultMatch();
    } else if (quickFilter == QuickFilter.yiji) {
      filter.leagueType = LqFilterType.all;
      filter.onSelectOneLevel();
      filterMatch(filter.getHideLeagueIdList());
    } else if (quickFilter == QuickFilter.jingcai) {
      filter.onSelectLeagueType(LqFilterType.jc);
      filterMatch(filter.getHideLeagueIdList());
    } else if (quickFilter == QuickFilter.qingbao) {
      onSelectDefaultMatch(type: quickFilter);
    } else if (quickFilter == QuickFilter.guandian) {
      onSelectDefaultMatch(type: quickFilter);
    }
    filter.savaFilterToLocal();
  }

  void onSelectDefaultMatch({QuickFilter type = QuickFilter.all}) {
    quickFilter = type;

    filter.leagueType = LqFilterType.all;
    filter.onSelectAll();
    filter.updateLeague();
    filterMatch([]);
    filter.savaFilterToLocal();
  }

  void onCloseBottomBar() {
    isBottomHide = true;
    update();
  }

  @override
  Future doRefresh() async {
    if (refreshC.headerState?.mode.isIdle == false) return;
    refreshC.callRefresh();
    // update();
  }

  @override
  String getTicketName(ZqListEntity match) {
    throw UnimplementedError();
  }
}
